// https://www.lintcode.com/problem/insertion-sort-list/

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: The head of linked list.
     */
    public ListNode insertionSortList(ListNode head) {
        // write your code here
        ListNode new_head = new ListNode(0); // Dummy节点，方便后续代码处理。
        while (head != null) {
            ListNode tmp = new_head, next = head.next;
            while ((tmp.next != null) && (tmp.next.val < head.val)) {
                tmp = tmp.next;
            }
            head.next = tmp.next;
            tmp.next = head;
            head = next;
        }
        return new_head.next;
    }
}